package com.cassio.guarapari.dao;

import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;

import com.cassio.guarapari.util.LogUtil;

public abstract class GenericDAO {
	
	private static final EntityManager em = DAOFactory.getEntityManager();
	
	
	protected static EntityManager getEm() {
		return em;
	}

	protected static EntityTransaction getTransaction() {
		return getEm().getTransaction();
	}
	
	public static <E> void persist(E entity) {
		try {
			getEm().persist(entity);
			getEm().refresh(entity);
		} catch (RuntimeException e) {
			LogUtil.log(e);
			throw e;
		}
	}

	public static <E> E merge(E entity) {
		try {
			E mergedEntity = getEm().merge(entity);
			return mergedEntity;
		} catch (RuntimeException e) {
			LogUtil.log(e);
			throw e;
		}
	}

	public static <E> void remove(E entity) {
		try {
			getEm().remove(entity);
		} catch (RuntimeException e) {
			LogUtil.log(e);
			throw e;
		}
	}

	public static <E> E findById(Class<E> clazz, Long id) {
		return getEm().find(clazz, id);
	}
	
}
